import { WechatyBuilder } from "wechaty";
interface IMessage {
  payload: {
    id: string;
    talkerId: string;
    text: string;
    timestamp: number;
    type: number;
    listenerId: string;
  };
}

class WeChaty {
  private static ins: any = null;
  bot: any = null;
  public onScanCallback: ((code: string) => void) | null = null;
  public onMessageCallback: ((money: string) => void) | null = null;
  public onLogout: (() => void) | null = null;
  public onloginCallback: (() => void) | null = null;

  constructor() {
    this.bot = WechatyBuilder.build();

    // 监听返回的登录二维码
    this.bot.on("scan", (code: any) => {
      if (this.onScanCallback) {
        this.onScanCallback(code);
      }
    });

    // 监听登录成功
    this.bot.on("login", () => {
      if (this.onloginCallback) {
        this.onloginCallback();
      }
    });

    this.bot.on("StarterBot", () => {
      if (this.onLogout) {
        this.onLogout();
      }
    });

    // 监听收到的消息
    this.bot.on("message", this.onMessage.bind(this));

    // 监听错误
    this.bot.on("error", (_err: any) => {
    });
  }
  onMessage({ payload }: IMessage) {
    // 7：文字消息
    // 14：赞赏码收款
    if (payload.type === 14) {
      const money = WeChaty.getIncomeForXml(payload.text);
      if (this.onMessageCallback) {
        this.onMessageCallback(money);
      }
    }
    return;
  }
  run(): Promise<string> {
    return new Promise((resolve) => {
      this.bot.on("scan", (code: any) => {
        resolve(code);
      });
      this.bot.start();
    });
  }

  public static getIncomeForXml(str: string) {
    const match = str.match(/收款金额￥(\d+(\.\d+)?)\n/);
    if (!match) {
      return "";
    }
    return match[1];
  }

  /**
   * 是否已经登录
   */
  public isLogin() {
    return WeChaty.ins.bot.isLoggedIn;
  }

  public static removeIns() {
    WeChaty.ins = null;
  }

  public static create(): WeChaty {
    if (!WeChaty.ins) {
      WeChaty.ins = new WeChaty();
    }

    return WeChaty.ins;
  }
}

export default WeChaty;
// new weChaty().run();
